/*
* Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.
* Description: image_mbuf_yuv_sender head file
*/

#ifndef IMAGE_MBUF_YUV_SENDER_H
#define IMAGE_MBUF_YUV_SENDER_H
#include "image_sender_base.h"
#include "mdc/cam/camera/cameradecodedmbufserviceinterface_skeleton.h"
#include "util.h"
#include "core/types.h"
#include "driver/ascend_hal.h"
#include "securec.h"
#include "mdc/cam/camera/cameraimagembufserviceinterface_skeleton.h"

#include "camera_data_head.h"

using namespace std;
using namespace cv;

using CamPubImageMbufSkeleton = mdc::cam::camera::skeleton::CameraImageMbufServiceInterfaceSkeleton;
using MbufHandle = uintptr_t;

class ImageMbufYuvSender : public ImageSenderBase<CamPubImageMbufSkeleton>
{
private:
    poolHandle handle {};
    float lastTime {0.0F};
    std::string sourceYuvPath;
    FILE *fp_yuv;

public:
    ImageMbufYuvSender() = default;
    ImageMbufYuvSender(uint32_t id,  cv::Size s, std::string dir) :  ImageSenderBase<CamPubImageMbufSkeleton>(id, s, dir)
    {
        sourceYuvPath = dir;
        if (dir.back() != '/') {
            sourceYuvPath += string("/") + "yuvSource.yuv";
        } else {
            sourceYuvPath += "yuvSource.yuv";
        }
#ifdef SAVE_SENDER_FILE
        fp_yuv = fopen(sourceYuvPath.c_str(), "wb+");
#endif
    }
    ~ImageMbufYuvSender()
    {
        if (dataSkeleton !=  nullptr) {
            dataSkeleton->StopOfferService();
            dataSkeleton = nullptr;
        }
        if (handle != nullptr) {
            halBuffDeletePool(handle);
        }
    } ;

    bool RegisterSender()
    {
        std::cout << "Begin register MBUF image sender." << std::endl;
        auto result = ImageSenderBase<CamPubImageMbufSkeleton>::RegisterSender();
        std::cout << "Finished to register MBUF image sender." << std::endl;
        return result;
    }

    int32_t BufCreatePool(const uint32_t blkSize, const uint32_t blkNum)
    {
        constexpr uint32_t alignSize = 32U;
        mpAttr attr;
        attr.devid  =  0;
        attr.mGroupId  =  0;
        attr.blkSize = ((blkSize  +  alignSize) - 1U)  & (~(alignSize  - 1));
        attr.blkNum = blkNum;
        attr.align = alignSize;
        attr.hugePageFlag = 1U;
        const int32_t ret = halBuffCreatePool(&attr,  &handle);
        if (ret != DRV_ERROR_NONE) {
            std::cout << "halBuffCreatePool error:" << ret << std::endl;
            return -1;
        }
        return 0;
    }

    int32_t BufGetMbuf(poolHandle &handle, uintptr_t &getMbuf) const
    {
        Mbuf *pMbuf = nullptr;
        const int32_t ret = halMbufAllocByPool(handle, &pMbuf);
        if (ret != 0) {
            std::cout << "halMbufAllocByPool error: " << ret << std::endl;
            return -1;
        }
        getMbuf = reinterpret_cast<uintptr_t>(pMbuf);
        return 0;
    }

    int32_t GetMbuf(poolHandle &pHandle, MbufHandle &pMbuf)
    {
        return BufGetMbuf(pHandle, pMbuf);
    }

    bool PackCameraHead(const YuvImageInfo &info, const uintptr_t &head)
    {
        //获取Mbuf指针及长度
        uintptr_t ptr;
        uint64_t size;
        const auto ret = GetMbufPtrLength(head, ptr, size);
        if (ret != 0) {
            std::cout << "GetMbufPtrLength error: " << ret << std::endl;
            return false;
        }
        const uint64_t headSize = sizeof(mdc::camera::CameraDataHead);
        std::cout << "--------SetMbufPtr(head, headSize)" << SetMbufPtr(head, headSize) << ",headSize=" << headSize << std::endl;
        if (headSize > size) {
            std::cout << "Head size " << headSize << " larger than " << size << std::endl;
            return false;
        }
        const auto pHead = reinterpret_cast<mdc::camera::CameraDataHead *>(ptr);
        if (memset_s(pHead, headSize, 0, headSize) != 0) {
            std::cout << " memset_s fail!"  << std::endl;
            return false;
        }
        pHead->seq = info.header.Seq;
        pHead->height = info.height;
        pHead->width = info.width;
        pHead->ebdInfo.expoNumValid = true;
        pHead->ebdInfo.expoNum = 2U; // 2个曝光时间
        pHead->ebdInfo.shutterTimeValid = true;
        pHead->ebdInfo.shutterTime[0U] = info.header.Stamp.Shutter1;
        pHead->ebdInfo.shutterTime[1U] = info.header.Stamp.Shutter2;
        pHead->ebdInfo.expStartTimeStamp.timesec = info.header.Stamp.ExpStartS;
        pHead->ebdInfo.expStartTimeStamp.timensec = info.header.Stamp.ExpStartNs;
        pHead->ebdInfo.expEndTimeStamp.timesec = info.header.Stamp.ExpEndS;
        pHead->ebdInfo.expEndTimeStamp.timensec = info.header.Stamp.ExpEndNs;
        pHead->auxInfo.pubTimeStamp.isValid = true;
        pHead->auxInfo.pubTimeStamp.timesec = info.sendTimeHigh;
        pHead->auxInfo.pubTimeStamp.timensec = info.sendTimeLow;
        pHead->auxInfo.fsyncTimeStamp.isValid = true;
        pHead->auxInfo.fsyncTimeStamp.timesec = info.header.Stamp.Sec;
        pHead->auxInfo.fsyncTimeStamp.timensec = info.header.Stamp.Nsec;
        return true;
    }
    int32_t AppendMbuf(const uintptr_t head, const uintptr_t mbufPtr) const
    {
        return BufChainAppend(head, mbufPtr);
    }

    int32_t BufChainAppend(const uintptr_t head, const uintptr_t mbufPtr) const
    {
        Mbuf *const pHead = reinterpret_cast<Mbuf *>(head);
        Mbuf *const pMbuf = reinterpret_cast<Mbuf *>(mbufPtr);
        const int32_t ret = halMbufChainAppend(pHead, pMbuf);
        if (ret != 0) {
            std::cout << "halMbufChainAppend error: " << ret << std::endl;
            return -1;
        }
        return 0;
    }

    int32_t GetMbufPtrLength(const MbufHandle &pMbuf, uintptr_t &ptr, uint64_t &len) const
    {
        if (BufGetDataPtr(pMbuf, ptr, len) != 0) {
            std::cout << "CopyToMbuf BufGetDataPtr error: " << std::endl;
            return -1;
        }
        return 0;
    }

    int32_t BufGetDataPtr(const uintptr_t in, uintptr_t &out, uint64_t &dataSize) const
    {
        Mbuf *const pSrc = reinterpret_cast<Mbuf *>(in);
        void *pData = nullptr;
        const int32_t ret = halMbufGetDataPtr(pSrc, &pData,  &dataSize);
        if (ret != 0) {
            std::cout << "MbufGetDataPtr error: " << ret <<  std::endl;
            return -1;
        }
        out = reinterpret_cast<uintptr_t>(pData);
        return 0;
    }

    int32_t SetMbufPtr(const MbufHandle &pMbuf,  const uint64_t &len) const
    {
        return BufSetDataLen(pMbuf, len);
    }

    int32_t BufSetDataLen(const uintptr_t setMbuf, const uint64_t len) const
    {
        Mbuf *const pMbuf = reinterpret_cast<Mbuf *>(setMbuf);
        const int32_t ret = halMbufSetDataLen(pMbuf, len);
        if (ret != 0) {
            std::cout << "halMbufSetDataLen error: " << ret <<  std::endl;
            return -1;
        }
        return 0;
    }

    int32_t BufFree(const uintptr_t in) const
    {
        Mbuf *const pSrc = reinterpret_cast<Mbuf *>(in);
        const int32_t ret = halMbufFree(pSrc);
        if (ret != 0) {
            std::cout << "MbufFree error: " << ret << std::endl;
            return -1;
        }
        return 0;
    }

    void SaveImage(const ara::core::String &instanceId,
                   const uint32_t &seq, const uintptr_t &ptr, const uint32_t &len) const
    {
        FILE *filePtr;
        const auto fileName = instanceId + "_" + std::to_string(seq) + ".yuv";
        filePtr = fopen(fileName.c_str(), "wb");
        if (filePtr != nullptr) {
            (void)fwrite(reinterpret_cast<uint8_t *>(ptr), static_cast<size_t>(len), 1U, filePtr);
            (void)fclose(filePtr);
            filePtr = nullptr;
        } else {
            std::cout << "yuv image save failed file name: " << fileName << std::endl;
        }
    }

    void FillImageAndSend(std::string imgPath, uint32_t seq, void *g_stopFlag) override
    {
        (void)g_stopFlag;
        std::string path = dir;
        std::string postfix = comPara.fileType;
        bool isLoop = comPara.loop;
        cout << "dir: " << dir << "\t" << "postfix :" << postfix << endl;
        std::vector<std::string> files;
        int32_t fileCnt = getFilesBySort(path, files, comPara.fileType);
        if (fileCnt == 0) {
            cout << "PATH:" << path << " has no files!" << endl;
            return;
        }
        do {
            for (auto &file : files) {
                int32_t w = imgSize.width;
                int32_t h = imgSize.height;
                FILE *yuv_file;
                yuv_file = fopen(file.c_str(), "rb");
                if (yuv_file == nullptr) {
                    cout << "Open yuv file failed!" << endl;
                    return;
                }
                int32_t frameSize = w * h * 3 / 2;
                fseek(yuv_file, 0, SEEK_END);
                int32_t fileSize = ftell(yuv_file);
                rewind(yuv_file);
                int32_t frameCount = fileSize / frameSize;
                char *yuvBuff = (char *)malloc(frameSize * sizeof(char));
                for (int32_t i = 0; i < frameCount; i++) {
                    Mat YUV420NV12;
                    YUV420NV12.create(h * 1.5, w, CV_8UC1);
                    memset(yuvBuff, 0, frameSize);
                    fread(yuvBuff, sizeof(char), frameSize, yuv_file);
                    memcpy(YUV420NV12.data, yuvBuff, frameSize);
                    uintptr_t head;
                    int32_t ret = GetMbuf(handle, head);
                    if (ret != 0) {
                        std::cout  << "GetMbuf head error"  << std::endl;
                        return;
                    }
                    YuvImageInfo yuvImageInfo;
                    yuvImageInfo.width = w;
                    yuvImageInfo.height = h;
                    //获取空闲Mbuf模块
                    uintptr_t mbufTmp;
                    ret = GetMbuf(handle, mbufTmp);
                    if (ret != 0) {
                        std::cout << "GetMbuf mbufTmp error" << std::endl;
                        return;
                    }
                    //获取mbuff指针及长度
                    uintptr_t outStream;
                    uint64_t mbufMaxLen;
                    uint64_t actualLen;
                    ret = GetMbufPtrLength(mbufTmp, outStream, mbufMaxLen);
                    if (ret != 0) {
                        std::cout << "GetMbufPtrLength error" << std::endl;
                        return;
                    }
                    actualLen = frameSize;
                    if (memcpy_s(reinterpret_cast<uint8_t *>(outStream), mbufMaxLen, YUV420NV12.data, actualLen) != 0) {
                        std::cout << "outStream memcpy_s failed" << std::endl;
                    }
                    //设置mbuf长度
                    ret = SetMbufPtr(mbufTmp, actualLen);
                    if (ret != 0) {
                        std::cout << "SetMbufPtr error" << std::endl;
                        BufFree(mbufTmp);
                        return;
                    }
                    //设置mbuf
                    yuvImageInfo.mbuffer = mbufTmp;
                    yuvImageInfo.length = static_cast<uint32_t>(actualLen);
                    if (!PackCameraHead(yuvImageInfo, head)) {
                        std::cout << "PackCameraHead error" << std::endl;
                        return;
                    }
                    auto apData = dataSkeleton->cameraImageMbufEvent.Allocate();
                    const uint32_t imageHeadType_ = 1U;
                    const uint32_t imageYuvSemiplanarType_ = 1001U;
                    const uint32_t mutiImageVersion_ = 0x1000U;
                    apData->type.push_back(imageHeadType_);
                    ret = AppendMbuf(head, yuvImageInfo.mbuffer);
                    if (ret != 0) {
                        std::cout << "AppendMbuf error" << ", ret" << ret << std::endl;
                        return;
                    }
                    apData->type.push_back(imageYuvSemiplanarType_);
                    apData->version = mutiImageVersion_;
                    apData->seq = seq;
                    apData->head = reinterpret_cast<rawBuffer *>(head);
#ifdef SAVE_SENDER_FILE
                    fwrite(YUV420NV12.data, 1, frameSize, fp_yuv);
#endif
                    dataSkeleton->cameraImageMbufEvent.Send(std::move(apData));
                    cout << "Begin send image. seq: " << seq << ", frameID: " << frameID << " path: " << file << endl;
                    seq++;
                    if (comPara.frequency != "") {
                        int32_t freq = atoi(comPara.frequency.c_str());
                        int32_t sleepTime = 1000000 / freq;
                        usleep(sleepTime);
                    } else {
                        usleep(1000000 / 30);//30hz
                    }
                }
                free(yuvBuff);
            }
        } while (isLoop);
#ifdef SAVE_SENDER_FILE
        fclose(fp_yuv);
#endif
    }
};



#endif // IMAGE_MBUF_YUV_SENDER_H
